﻿using Microsoft.Data.Sqlite;
using MySql.Data.MySqlClient;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Concurrent;
using System.Data.SqlClient;

namespace Dapper.Core
{
    /// <summary>
    /// Sql 类型
    /// </summary>
    public static class SqlProvider
    {
        /// <summary>
        /// 数据库提供器连接对象类型集合
        /// </summary>
        internal static readonly ConcurrentDictionary<DatabaseType, Type> SqlProviderDbConnectionTypeCollection;

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static SqlProvider()
        {
            SqlProviderDbConnectionTypeCollection = new ConcurrentDictionary<DatabaseType, Type>();
        }

        /// <summary>
        /// 获取数据库连接对象类型
        /// </summary>
        /// <param name="sqlProvider"></param>
        /// <returns></returns>
        internal static Type GetDbConnectionType(DatabaseType sqlProvider)
        {
            return SqlProviderDbConnectionTypeCollection.GetOrAdd(sqlProvider, Function);

            // 本地静态方法 => 获取对应数据库连接对象
            static Type Function(DatabaseType sqlProvider)
            {
                dynamic databaseDbConnectionType = null;
                switch (sqlProvider)
                {
                    case DatabaseType.SqlServer:
                        databaseDbConnectionType = new SqlConnection();
                        break;
                    case DatabaseType.Oracle:
                        databaseDbConnectionType = new OracleConnection();
                        break;
                    case DatabaseType.MySql:
                        databaseDbConnectionType = new MySqlConnection();
                        break;
                    case DatabaseType.SQLite:
                        databaseDbConnectionType = new SqliteConnection();
                        break;
                    case DatabaseType.Npgsql:
                        databaseDbConnectionType = new NpgsqlConnection();
                        break;
                }

                // 加载数据库连接对象类型
                var dbConnectionType = databaseDbConnectionType.GetType();

                return dbConnectionType;
            }
        }
    }
}
